package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.entity.rBuyappMain;
import com.isunland.managesystem.entity.rBuyappSub;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  采购明细详情
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/6/15 14:18
 */
public class BuyDetailFragment extends BaseFragment implements View.OnClickListener {
  protected static String EXTRA_CONTENT = BuyDetailFragment.class.getSimpleName() + "EXTRA_CONTENT";
  protected static String EXTRA_MAIN = BuyDetailFragment.class.getSimpleName() + "EXTRA_MAIN";
  @BindView(R.id.sl_materialKindName) SingleLineView slMaterialKindName;
  @BindView(R.id.sl_materialName) SingleLineView slMaterialName;
  @BindView(R.id.sl_mtype) SingleLineView slMtype;
  @BindView(R.id.sl_munit) SingleLineView slMunit;
  @BindView(R.id.sl_mainproject) SingleLineView slMainproject;
  @BindView(R.id.sl_mprice) SingleLineView slMprice;
  @BindView(R.id.sl_mnumber) SingleLineView slMnumber;
  @BindView(R.id.sl_mdNumber) SingleLineView slMdNumber;
  @BindView(R.id.sl_msumPrice) SingleLineView slMsumPrice;
  @BindView(R.id.sl_mfactoryName) SingleLineView slMfactoryName;
  @BindView(R.id.sl_mstatusName) SingleLineView slMstatusName;
  @BindView(R.id.sl_appRatifyNum) SingleLineView slAppRatifyNum;
  @BindView(R.id.sl_remark) SingleLineView slRemark;
  private int NEW = 0;
  private int PUBLISH = 1;
  private int ADD = 2;
  private int REQUEST_MATERIALKIND = 3;
  private int REQUEST_MATERIA = 4;
  private int REQUEST_FACTORY = 5;

  private rBuyappSub subContent;
  private rBuyappMain mainContent;
  private String mMainId;
  private String mId;
  private String materialKindCode;
  private String materialCode;
  private String mfactoryId;
  private int menuType;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.buyDetailed);
    mainContent = (rBuyappMain) getArguments().getSerializable(EXTRA_MAIN);
    mMainId = mainContent.getId();
    subContent = (rBuyappSub) getArguments().getSerializable(EXTRA_CONTENT);

    if (subContent == null) {
      //添加
      mId = UUID.randomUUID().toString();
      menuType = ADD;
      materialKindCode = "";
      materialCode = "";
      mfactoryId = "";
    }
    if (subContent != null) {
      //详情
      mId = subContent.getId();
      materialKindCode = subContent.getMaterialKindCode();
      materialCode = subContent.getMaterialCode();
      mfactoryId = subContent.getMfactoryId();
      //String dataStatus = subContent.getMstatusCode();
      String dataStatus = mainContent.getBuyappStatusName();
      if (DataStatus.NEW.equalsIgnoreCase(dataStatus) || DataStatus.ABORT.equalsIgnoreCase(
          dataStatus)) {
        menuType = NEW;
      } else {
        menuType = PUBLISH;
      }
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    ButterKnife.bind(this, rootView);
    return rootView;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    if (menuType == ADD) {
      //保存和删除
      inflater.inflate(R.menu.menu_save_delete, menu);
      menu.getItem(1).setVisible(false);
    } else if (menuType == NEW) {
      //保存和删除
      inflater.inflate(R.menu.menu_save_delete, menu);
    } else {
      super.onCreateOptionsMenu(menu, inflater);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave();
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        volleyPostDel();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  /*判断必填项*/
  private boolean isCorrectInput() {
    if (TextUtils.isEmpty(slMaterialKindName.getTextContent())
        || TextUtils.isEmpty(slMaterialName.getTextContent())
        || TextUtils.isEmpty(slMprice.getTextContent())
        || TextUtils.isEmpty(slMnumber.getTextContent())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    } else {
      return true;
    }
  }

  /*保存*/
  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_BUY_DETAIL_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainid", mMainId);
    params.put("id", mId);
    params.put("materialKindCode", materialKindCode);
    params.put("materialKindName", slMaterialKindName.getTextContent());
    params.put("materialCode", materialCode);
    params.put("materialSelfCode", materialCode);
    params.put("materialName", slMaterialName.getTextContent());
    params.put("mtype", slMtype.getTextContent());
    params.put("munit", slMunit.getTextContent());
    params.put("mprice", slMprice.getTextContent());
    params.put("mnumber", slMnumber.getTextContent());
    params.put("msumPrice", slMsumPrice.getTextContent());
    params.put("mdNumber", slMdNumber.getTextContent());
    params.put("mfactoryName", slMfactoryName.getTextContent());
    params.put("mfactoryId", mfactoryId);
    params.put("remark", slRemark.getTextContent());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  /*删除*/
  private void volleyPostDel() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_BUY_DETAIL_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(json, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    };
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_buy_detail;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    if (subContent != null) {
      //详情
      slMaterialKindName.setTextContent(subContent.getMaterialKindName());
      slMaterialName.setTextContent(subContent.getMaterialName());
      slMtype.setTextContent(subContent.getMtype());
      slMunit.setTextContent(subContent.getMunit());
      slMprice.setTextContent(subContent.getMprice());
      slMnumber.setTextContent(subContent.getMnumber());
      slMsumPrice.setTextContent(subContent.getMsumPrice());
      slMdNumber.setTextContent(subContent.getMdNumber());
      slMfactoryName.setTextContent(subContent.getMfactoryName());
      MyUtils.switchDataStutus(getActivity(), slMstatusName.getViewContent(),
          subContent.getMstatusName());
      slAppRatifyNum.setTextContent(subContent.getAppRatifyNum());
      slRemark.setTextContent(subContent.getRemark());
    } else {
      //添加
      slMsumPrice.setTextContent("0.0");
      MyUtils.switchDataStutus(getActivity(), slMstatusName.getViewContent(), DataStatus.NEW);
    }
    if (PUBLISH == menuType) {
      //不允许编辑
      slMaterialKindName.getViewContent().setEnabled(false);
      slMaterialName.getViewContent().setEnabled(false);
      slMtype.getViewContent().setEnabled(false);
      slMunit.getViewContent().setEnabled(false);
      slMprice.getViewContent().setEnabled(false);
      slMnumber.getViewContent().setEnabled(false);
      slMsumPrice.getViewContent().setEnabled(false);
      slMdNumber.getViewContent().setEnabled(false);
      slMfactoryName.getViewContent().setEnabled(false);
      slRemark.getViewContent().setEnabled(false);
    }

    slMaterialKindName.setOnClickContentListener(this);
    slMaterialName.setOnClickContentListener(this);
    slMfactoryName.setOnClickContentListener(this);
    slMnumber.getTvContent().addTextChangedListener(textWatcher());
    slMprice.getTvContent().addTextChangedListener(textWatcher());
  }

  @Override public void onClick(View view) {
    if (!(view.getTag() instanceof Integer)) return;
    int id = (int) view.getTag();
    switch (id) {
      case R.id.sl_materialKindName:
        //物料类别
        volleyPostMaterialKind();
        break;
      case R.id.sl_materialName:
        //物料名称
        if (!TextUtils.isEmpty(slMaterialKindName.getTextContent())) {
          volleyPostMaterial();
        } else {
          ToastUtil.show("请先选择物料类别!");
        }
        break;
      case R.id.sl_mfactoryName:
        //生产厂家: 客户
        //跳转到客户名录列表界面,单选
        Intent customer = new Intent(getActivity(), CustomerListChooseActivity.class);
        startActivityForResult(customer, REQUEST_FACTORY);
        break;
    }
  }

  private TextWatcher textWatcher() {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      }

      @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        double sumPrice;
        if (!TextUtils.isEmpty(slMprice.getTextContent()) && !TextUtils.isEmpty(
            slMnumber.getTextContent())) {
          double number = Double.parseDouble(slMnumber.getTextContent());
          double price = Double.parseDouble(slMprice.getTextContent());
          sumPrice = number * price;
        } else {
          sumPrice = 0.0;
        }
        slMsumPrice.setTextContent(String.valueOf(sumPrice));
      }

      @Override public void afterTextChanged(Editable editable) {

      }
    };
  }

  /* 物料类别*/
  private void volleyPostMaterialKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("物料类别");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_BUY_MATERIE_LOM);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dataStatus", "publish")
            .put("type", "app")
            .put("materialKindCodeLike", mainContent.getMaterialKindCode()));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_MATERIALKIND);
  }

  /* 物料名称*/
  private void volleyPostMaterial() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("物料名称");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_BUY_MATERIE_LOM);
    params.setSelectType(SimpleTreeListParams.ONLY_CHILD);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dataStatus", "publish")
            .put("materialKindCodeLike", materialKindCode)
            .put("type", "app")
            .put("ifContainProduct", "true")
            .put("ifMNameWithMtype", "true")
            .put("ifMNameWithStockNum", "true"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_MATERIA);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;

    if (requestCode == REQUEST_MATERIALKIND) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      materialKindCode = item.getId();
      slMaterialKindName.setTextContent(item.getName());
    }
    if (requestCode == REQUEST_MATERIA) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      materialCode = item.getFlag();
      slMaterialName.setTextContent(item.getName());
      slMtype.setTextContent(item.getExtParam());//规格型号
      slMunit.setTextContent(item.getExtParam2());//基本单位
      slMdNumber.setTextContent(item.getExtParam3());//已办数量
    }
    if (requestCode == REQUEST_FACTORY) {
      String factoryName = data.getStringExtra("customerName");
      mfactoryId = data.getStringExtra("customerId");
      slMfactoryName.setTextContent(factoryName);
    }
  }

  public static BuyDetailFragment newInstance(rBuyappSub content, rBuyappMain mainContent) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putSerializable(EXTRA_MAIN, mainContent);
    BuyDetailFragment fragment = new BuyDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
